package com.hos.db.manager;

import com.gexin.rp.sdk.base.uitls.MD5Util;
import com.hos.db.create.user.UserSysTable;
import com.hos.db.entity.UserSysEntity;
import com.hos.net.req.sys.SysRegisterReq;
import com.hos.net.res.BaseResponse;
import com.hos.net.res.MsgHint;
import com.hos.utile.DLog;
import com.hos.utile.DateUtile;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.simple.ParameterizedBeanPropertyRowMapper;

import java.util.Date;
import java.util.List;

//系统
public class SysManager {

    private static SysManager userPatsManager;

    public static SysManager getInstance() {
        if (userPatsManager == null) {
            userPatsManager = new SysManager();
        }
        return userPatsManager;
    }

    /**
     * @param jdbcTemplate
     * @param req          用户注册参数
     * @return 注册结果
     */
    public String sysRegister(JdbcTemplate jdbcTemplate, SysRegisterReq req) {
        boolean isExit = isRegister(jdbcTemplate, req.account);
        if (isExit) {
            return new MsgHint("该账号已存在").toJson();
        }
        String response = new MsgHint("注册失败").toJson();
        String sysId = req.account;
        String sql = "INSERT INTO " + UserSysTable.tableName
                + "("
                + UserSysTable.tableSysId + ","
                + UserSysTable.tableSysName + ","
                + UserSysTable.tableSysAccount + ","
                + UserSysTable.tableSysPwd + ","
                + UserSysTable.tableSysPhone + ","
                + UserSysTable.tableSysRegisterTime
                + ")"
                + " VALUES (?,?, ?, ?,?, ?)";
        try {
            int status = jdbcTemplate.update(sql,
                    new Object[]{sysId, req.name, req.account,
                            MD5Util.getMD5Format(req.pwd),
                            req.account, new Date()});
            if (status > 0) {
                UserSysEntity user = new UserSysEntity();
                user.setSysAccount(req.account);
                user.setSysName(req.name);
                response = user.toJson("注册成功");
            }
        } catch (Exception e) {
            DLog.e("注册成功：" + e.getMessage());
        }
        return response;
    }

    /**
     * @param jdbcTemplate jdbc
     * @param sysAccount   登录账户
     * @return
     */
    public String sysLoginReq(JdbcTemplate jdbcTemplate, String sysAccount, String sysPwd) {
        sysPwd = MD5Util.getMD5Format(sysPwd);
        String sql = "SELECT * FROM " + UserSysTable.tableName + " WHERE "
                + UserSysTable.tableSysAccount + " = " + sysAccount + " and "
                + UserSysTable.tableSysPwd + " = " + "'" + sysPwd + "'";
        DLog.e(sql);
        List<UserSysEntity> users = sysQuery(jdbcTemplate, sql);
        if (users == null || users.size() == 0) {
            return new MsgHint("账号或者密码错误").toJson();
        }
        String loginTime = DateUtile.getDateFormat(new Date(), DateUtile.DATA_FORMAT_YMD_HMS);
        String token = MD5Util.getMD5Format(sysAccount + loginTime);
        UserSysEntity user = users.get(0);
        user.setSysToken(token);
        createToken(jdbcTemplate, sysAccount, token, loginTime);
        //
        BaseResponse<UserSysEntity> baseResponse = new BaseResponse();
        baseResponse.obj = user;
        baseResponse.token = token;
        return baseResponse.toJson("登录成功");
    }

    /**
     * @param jdbcTemplate jdbc
     * @param sysAccount   查询账号
     * @return true 账号存在
     */
    public boolean isRegister(JdbcTemplate jdbcTemplate, String sysAccount) {
        String sql = "SELECT * FROM " + UserSysTable.tableName + " WHERE "
                + UserSysTable.tableSysAccount + " = " + sysAccount;
        List<UserSysEntity> users = sysQuery(jdbcTemplate, sql);
        return users != null && users.size() > 0;
    }

    /**
     * 更新密码
     *
     * @param jdbcTemplate
     * @param phone
     * @param pwd
     * @return
     */
    public boolean updatePwdRest(JdbcTemplate jdbcTemplate, String phone, String pwd) {
        //
        pwd = MD5Util.getMD5Format(pwd);
        //UPDATE cs_user SET gender = '男' WHERE id = 4
        String sql = "UPDATE " + UserSysTable.tableName
                + " SET "
                + UserSysTable.tableSysPwd + " = '" + pwd+"'"
                + " WHERE "
                + UserSysTable.tableSysPhone + " = " + phone;
        int j = jdbcTemplate.update(sql);
        return j > 0;
    }

    /**
     * 按手机号获取用户
     *
     * @param jdbcTemplate
     * @param phone
     * @return
     */
    public UserSysEntity getUserForPhone(JdbcTemplate jdbcTemplate, String phone) {
        UserSysEntity user = null;
        String sql = "SELECT * FROM " + UserSysTable.tableName + " WHERE "
                + UserSysTable.tableSysPhone + " = " + phone;
        List<UserSysEntity> users = sysQuery(jdbcTemplate, sql);
        if (users != null && users.size() > 0) {
            user = users.get(0);
        }
        return user;
    }

    //创建token
    public void createToken(JdbcTemplate jdbcTemplate, String sysAccount, String token, String time) {
        String sql = "update  " + UserSysTable.tableName
                + " set "
                + UserSysTable.tableSysToken + " = '" + token + "'"
                + " , "
                + UserSysTable.tableSysLoninTime + " = '" + time+"'"
                + " WHERE "
                + UserSysTable.tableSysAccount + " = " + sysAccount;
        jdbcTemplate.update(sql);
    }

    //校验token
    public UserSysEntity verifyTokenUser(JdbcTemplate jdbcTemplate, String token) {
        UserSysEntity user = null;
        if (token == null || token == "") {
            return user;
        }
        String sql = "SELECT * FROM " + UserSysTable.tableName + " WHERE "
                + UserSysTable.tableSysToken + " = '" + token+"'";
        List<UserSysEntity> users = sysQuery(jdbcTemplate, sql);

        if (users != null && users.size() > 0) {
            user = users.get(0);
        }
        if (users != null) {
            updateToken(jdbcTemplate, token);
        }
        return user;
    }

    //更新token
    private void updateToken(JdbcTemplate jdbcTemplate, String token) {
        String loginTime = DateUtile.getDateFormat(new Date(), DateUtile.DATA_FORMAT_YMD_HMS);
        String sql = "update  " + UserSysTable.tableName
                + " set "
                + UserSysTable.tableSysLoninTime + " = '" + loginTime+"'"
                + " WHERE "
                + UserSysTable.tableSysToken + " = '" + token + "'";
        jdbcTemplate.update(sql);
    }

    private List<UserSysEntity> sysQuery(JdbcTemplate jdbcTemplate, String sql) {
        List<UserSysEntity> users = null;
        try {
            users = jdbcTemplate.query(sql,
                    ParameterizedBeanPropertyRowMapper.newInstance(UserSysEntity.class));
            DLog.e("查询成功：==========");
        } catch (Exception e) {
            DLog.e("查询失败：" + e.getMessage());
        }
        return users;
    }
}
